package com.yufei.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ParallelExecutor <PType>{
	private int threadNum=1;
	private Collection<PType> collection;
	private Worker<PType> worker=null;
	

	public ParallelExecutor(int threadNum, Collection<PType> collection,
			Worker<PType> worker) {
		super();
		this.threadNum = threadNum;
		this.collection = collection;
		this.worker = worker;
	}

public void execute(){
	Thread thread=null;
	final List<List<PType>> lists=CommonUtil.splitKs(collection, collection.size()/threadNum);
	int finalGroupCount=lists.size();
	final ThreadLocal<Worker> workThreadLocal=new ThreadLocal<Worker>();
	workThreadLocal.set(this.worker);
	
	for(int i=0;i<threadNum+1;i++){
		if(i>finalGroupCount){
			continue;
		}
		
		final List<PType> subCollection=lists.get(i);
		thread=new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				workThreadLocal.set(worker);

				Worker worker=workThreadLocal.get();
				//worker.setCollection(subCollections);
				worker.run(subCollection);
			}
		});
		
		thread.start();
		/*try {
			thread.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		//.run(runs);
	}
	
	
	
}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Collection<String> collection=new ArrayList<String>();
		for(int i=0;i<10000;i++){
			collection.add(String.valueOf(i));
		}
		ParallelExecutor<String> parallel=new ParallelExecutor<>(3, collection, new Worker<String>() {

			@Override
			public void run(Collection<String> collection) {
				// TODO Auto-generated method stub
				for(String str:collection){
					System.out.print(str+"\n");
				/*	try {
						Thread.currentThread().sleep(1000*3);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
				}
			}
		});
		parallel.execute();

	}

}
